package cn.com.dhc.danlu.business.shopcar.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.delivery.order.decorate.Visitable;
import cn.com.dhc.danlu.activity.delivery.order.viewholder.BaseViewHolder;
import cn.com.dhc.danlu.business.shopcar.bean.MerchBean;
import cn.com.dhc.danlu.business.shopcar.bean.PromotionBean;
import cn.com.dhc.danlu.business.shopcar.bean.SellerBean;
import cn.com.dhc.danlu.business.shopcar.bean.ShopCarItem;
import cn.com.dhc.danlu.business.shopcar.bean.WrapDealerAttr;
import cn.com.dhc.danlu.business.shopcar.callback.IDataChangeCallback;
import cn.com.dhc.danlu.business.shopcar.callback.IMerchDataChangeCallback;
import cn.com.dhc.danlu.business.shopcar.callback.ISellerClickCallback;
import cn.com.dhc.danlu.business.shopcar.typefactory.IShopCarTypeFactory;
import cn.com.dhc.danlu.business.shopcar.typefactory.ShopCarTypeFactory;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.BaseRecyclerviewAdapter;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.DelShoppingCartRequest;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.DelShoppingCartRequest.DelList;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.GiftListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.MerchWraper;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean.PromotionModelListBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;


/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-27 17:31
 *
 * <p>
 * 购物车 adapter
 * </p>
 */
public class ShopCarAdapter extends BaseRecyclerviewAdapter<BaseViewHolder> implements ISellerClickCallback, IMerchDataChangeCallback {
    private ArrayMap<String, List<GiftListBean>> merchGiftMap;
    private IDataChangeCallback onDataChange;
    private IShopCarTypeFactory typeFactory;
    private Context context;
    private BigDecimal totalPrice;

    public ShopCarAdapter(Context context, IDataChangeCallback onDataChange) {
        super();

        this.context = context;
        this.onDataChange = onDataChange;
        this.merchGiftMap = new ArrayMap<>();
        this.typeFactory = new ShopCarTypeFactory();
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
        return typeFactory.createViewHolder(viewType, view, this);
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        final Visitable visitable = (Visitable) getItemByPos(position);
        holder.setData(visitable);
    }

    @Override
    public int getItemViewType(int position) {
        return ((Visitable) getItemByPos(position)).type(typeFactory);
    }

    @Override
    public void onMerchSel(int sellerIndex, int merchIndex) {
        // 修正促销中的属性
        MerchBean merchBean = (MerchBean) getDatas().get(merchIndex);
        refixedPromotion(merchBean, null, true);
        // 设置商店及其商品的选中状态
        setStoreSelState(sellerIndex);
        // 设置外部按钮的全选状态
        setSelAllState();
        // 通知外部更新
        noticeUpdate();

        notifyDataSetChanged();
    }

    @Override
    public void refreshAllData(@NonNull List datas) {
        super.refreshAllData(datas);

        setSelAllState();
        noticeUpdate();
    }

    @Override
    public void onMerchCountChange(int sellerIndex, int merchIndex, List<GiftListBean> giftList) {
        // 通知外部更新
        refixedPromotion((MerchBean) getDatas().get(merchIndex), giftList, false);
        noticeUpdate();
        notifyDataSetChanged();
    }

    @Override
    public void showPromotionsSelect(int merchIndex) {
        onDataChange.showPromotionSelect(merchIndex);
    }

    /**
     * 计算商品总价
     *
     * @return 商品总价
     */
    private BigDecimal calculateTotalPrice() {
        // TODO: 2017/3/9 完成商品总价的计算 @lyf #ok
        // 商品原价
        totalPrice = new BigDecimal(0);
        // 扣除优惠、促销的价格
        BigDecimal fixexTotalPrice = new BigDecimal(0);
        // 1. 获取映射关系表，明确需要计算价格的商品
        SparseArray<List<Integer>> selleMerchMap = getSellerMerchMap();

        for (int i = 0; i < selleMerchMap.size(); i++) {
            // 获得优惠信息
            PromotionBean promotion = (PromotionBean) getDatas().get(((SellerBean) getDatas().get(selleMerchMap.keyAt(i))).getPromotionIndex());
            // 优惠掉价格
            BigDecimal sellerDiscountPrice = new BigDecimal(0);
            // 商家商品总价
            BigDecimal sellerTotalPrice = new BigDecimal(0);

            for (Integer index : selleMerchMap.valueAt(i)) {
                if (getDatas().get(index) instanceof MerchBean) {
                    MerchBean merch = (MerchBean) getDatas().get(index);
                    BigDecimal unitPrice = new BigDecimal(merch.getUnitPrice());
                    BigDecimal merchCount = new BigDecimal(merch.getMerchQuantity());
                    // 2. 计算原始价格
                    // FIXME: 2017/3/12 需要考虑到优惠 & 促销 @lyf #ok
                    // FIXME: 2017/3/12 还需要考虑到限购 @lyf #ok
                    // 原始商品总价
                    sellerTotalPrice = sellerTotalPrice.add(unitPrice.multiply(merchCount));
                    if (merch.isSelPromotion() && promotion.isValid()) {
                        // 计算一下价格，各种优惠什么的
                        PromotionModelListBean promotionInfo = merch.getPromotionModelList().get(merch.getSelPromotionIndex());

                        if (promotionInfo.getIsPromotion().equals("1")) {
                            // 促销值校验
                            if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1.equals(promotionInfo.getPromotionType())) {
                                if (CommonConst.PromotionConst.REDUCTION_TYPE_0.equals(promotionInfo.getReductionType())) {
                                    // 满减单
                                    BigDecimal unitDiffPrice = new BigDecimal(promotionInfo.getDiffPrice());
                                    sellerDiscountPrice = sellerDiscountPrice.add(unitDiffPrice.multiply(merchCount));
                                    merch.setAveragePrice(unitPrice.subtract(unitDiffPrice));
                                } else if (CommonConst.PromotionConst.REDUCTION_TYPE_1.equals(promotionInfo.getReductionType())) {
                                    // 满减总
                                    // 该商品总价减去的价格
                                    BigDecimal sellerDiffPrice = new BigDecimal(promotionInfo.getDiffPrice());
                                    sellerDiscountPrice = sellerDiscountPrice.add(sellerDiffPrice);
                                    merch.setAveragePrice(unitPrice);
                                }
                                refixedPromotion(merch, null, false);
                            } else if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4.equals(promotionInfo.getPromotionType())) {
                                sellerDiscountPrice = sellerDiscountPrice.add(new BigDecimal(promotionInfo.getDiffPrice()));
                            } else {
                                merch.setAveragePrice(unitPrice);
                            }
                        }
                    } else {
                        merch.setAveragePrice(unitPrice);
                    }
                }
            }

            totalPrice = totalPrice.add(sellerTotalPrice);
            fixexTotalPrice = fixexTotalPrice.add(sellerTotalPrice.subtract(sellerDiscountPrice));

            if (sellerDiscountPrice.compareTo(new BigDecimal(0)) == 0) {
                promotion.setMsgReduce(null);
            } else {
                promotion.setMsgReduce(CommonUtils.fenToYuan(sellerDiscountPrice).toPlainString());
            }
        }

        // 3. 返回
        return fixexTotalPrice;
    }

    /**
     * 设置商店及其商品的选中状态
     *
     * @param storeIndex
     *         商店的 index
     */
    private void setStoreSelState(int storeIndex) {
        boolean goodsSelAll = isMerchesSelAll((SellerBean) getItemByPos(storeIndex));
        // 设置商店选中状态
        ((SellerBean) getItemByPos(storeIndex)).setSelected(goodsSelAll);
        // 如果商店存有推销区，设置选中状态
        if (((SellerBean) getItemByPos(storeIndex)).hasPromotionArea()) {
            ((PromotionBean) getItemByPos(((SellerBean) getItemByPos(storeIndex)).getPromotionIndex())).setSelected(goodsSelAll);
        }
    }

    /**
     * 商家的商品是否全部选中
     *
     * @param seller
     *         商家
     *
     * @return true - 全部选中
     */
    private boolean isMerchesSelAll(SellerBean seller) {
        boolean merchesSelAll = true;
        for (Integer index : seller.getMerchIndex()) {
            merchesSelAll = merchesSelAll && ((MerchBean) getItemByPos(index)).isSelected();
        }
        return merchesSelAll;
    }

    /**
     * 设置全部选中的按钮状态
     */
    public void setSelAllState() {
        boolean selAll = true;
        if (getDatas().isEmpty()) {
            selAll = false;
        } else {
            for (int i = 0; i < getDatas().size(); i++) {
                if (getDatas().get(i) instanceof SellerBean) {
                    selAll = selAll && ((SellerBean) getDatas().get(i)).isSelected();
                }
            }
        }
        onDataChange.onSelAll(selAll);
        noticeUpdate();
    }

    @Override
    public void onStoreSel(int sellerIndex, List<Integer> merchIndex, int promotionIndex, boolean isSelected) {
        if (0 != promotionIndex) {
            ((PromotionBean) getItemByPos(promotionIndex)).setSelected(isSelected);
        }

        for (int index : merchIndex) {
            MerchBean merch = ((MerchBean) getItemByPos(index));
            merch.setSelected(isSelected);
            refixedPromotion(merch, null, true);
        }

        setSelAllState();
        noticeUpdate();
        notifyDataSetChanged();
    }

    /**
     * 通知界面更新
     */
    private void noticeUpdate() {
        // 计算价格，并回调给外部
        onDataChange.onTotalPriceChange(calculateTotalPrice(), totalPrice);
        // 判断是否满足支付条件，并回调给外面
        onDataChange.onCanPay(getCannotPaySeller().isEmpty());
    }

    /**
     * 设置是否处于编辑装状态
     *
     * @param inEdited
     *         编辑状态， true = 编辑状态， false = 结算状态
     */
    public void setInEdited(boolean inEdited) {
        for (int i = 0; i < getDatas().size(); i++) {
            ((ShopCarItem) getDatas().get(i)).setEditMode(inEdited);
        }

        notifyDataSetChanged();
    }

    /**
     * 选择全部
     *
     * @param isSelected
     *         选中状态
     */
    public void selectAll(boolean isSelected) {
        for (int i = 0; i < getDatas().size(); i++) {
            ((ShopCarItem) getDatas().get(i)).setSelected(isSelected);
        }

        noticeUpdate();
        notifyDataSetChanged();
    }

    /**
     * 删除选中的数据
     */
    public void delSelItems() {
        // 1. 上传服务器
        DelShoppingCartRequest request = new DelShoppingCartRequest();
        request.setToken(agent.getToken());
        DelList merchDel;
        List<DelList> merchList = new ArrayList<>();
        SparseArray<List<Integer>> sellerMerchMap = getSellerMerchMap();
        for (int i = 0; i < sellerMerchMap.size(); i++) {
            for (int j = 0; j < sellerMerchMap.valueAt(i).size(); j++) {
                if (getDatas().get(sellerMerchMap.valueAt(i).get(j)) instanceof MerchBean) {
                    merchDel = new DelList();
                    merchDel.setMerchId(((MerchBean) getDatas().get(sellerMerchMap.valueAt(i).get(j))).getMerchId());
                    merchDel.setShoppingCartId(((MerchBean) getDatas().get(sellerMerchMap.valueAt(i).get(j))).getId());
                    merchList.add(merchDel);
                }
            }
        }
        request.setDelList(merchList);

        if (merchList.isEmpty()) {
            ToastUtil.getInstance().show(R.string.shopping_cart_delete_tip_noselected);
            return;
        } else {
            agent.getApi()
                    .delShoppingCartByProductId(request)
                    .compose(OperatorUtils.defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<BaseResponse>(context, R.string.tips_del) {

                        @Override
                        protected void onSuccess(BaseResponse baseResponse) {
                            // 1. 先删除数据 - 验证通过
                            delInvalidItems();
                            // 2. 修正 index - 验证通过
                            refixedIndex();
                            // 3. 更新外部 UI
                            noticeUpdate();
                            onDataChange.onDelSuccess(getDatas().size());
                            notifyDataSetChanged();
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(displayMessage);
                            // TODO: 2017/3/13 重新加载数据 @lyf #ok
                            onDataChange.onDelfailed();
                        }
                    });
        }
    }

    /**
     * 删除无效数据
     */
    private void delInvalidItems() {
        for (int i = 0; i < getDatas().size(); i++) {
            if (((ShopCarItem) getDatas().get(i)).isSelected()) {
                // 删除当前选中的数据
                getDatas().remove(i);
                i--;
            }
        }
    }

    /**
     * 重新修正删除后的数据 index
     */
    private void refixedIndex() {
        if (null == getDatas() || getDatas().isEmpty()) {
            return;
        }

        int storeIndex = 0;
        for (int i = 0; i < getDatas().size(); i++) {
            if (getDatas().get(i) instanceof SellerBean) {
                storeIndex = i;
                // 清理原有的商家所有的商品 index 集合
                ((SellerBean) getDatas().get(i)).getMerchIndex().clear();
            } else if (getDatas().get(i) instanceof MerchBean) {
                // 重新设置商品所属的商家 index
                ((MerchBean) getDatas().get(i)).setSellerIndex(storeIndex);
                // 重新向商家的所引用添加商品的 index
                ((SellerBean) getDatas().get(storeIndex)).getMerchIndex().add(i);
            } else if (getDatas().get(i) instanceof PromotionBean) {
                // 添加推销区的 index
                ((SellerBean) getDatas().get(storeIndex)).setPromotionIndex(i);
            }
        }
    }

    /**
     * 获取不可支付的商家
     *
     * @return 没有支付资格的商家 集合
     */
    public List<WrapDealerAttr> getCannotPaySeller() {
        // 1. 获取映射关系表，明确需要计算价格的商品
        SparseArray<List<Integer>> selleMerchMap = getSellerMerchMap();
        // 经销商的包装集合
        List<WrapDealerAttr> sellerCannotPay = new ArrayList<>();

        for (int i = 0; i < selleMerchMap.size(); i++) {
            // 获得商家信息
            SellerBean seller = (SellerBean) getDatas().get(selleMerchMap.keyAt(i));
            // 获得优惠信息
            PromotionBean promotion = (PromotionBean) getDatas().get(seller.getPromotionIndex());
            // 原始总价
            BigDecimal sellerTotalPrice = new BigDecimal(0);
            // 总优惠价格
            BigDecimal sellerDiscountPrice = new BigDecimal(0);

            for (Integer index : selleMerchMap.valueAt(i)) {

                if (getDatas().get(index) instanceof MerchBean) {
                    MerchBean merch = (MerchBean) getDatas().get(index);
                    BigDecimal unitPrice = new BigDecimal(merch.getUnitPrice());
                    BigDecimal merchCount = new BigDecimal(merch.getMerchQuantity());

                    // 2. 计算原始价格
                    sellerTotalPrice = sellerTotalPrice.add(unitPrice.multiply(merchCount));

                    if (merch.isSelPromotion() && merch.isEnable() && merch.isSelected() && promotion.isValid()) {
                        // 计算一下价格，各种优惠什么的
                        PromotionModelListBean promotionInfo = merch.getPromotionModelList().get(merch.getSelPromotionIndex());

                        // 促销值校验
                        if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1.equals(promotionInfo.getPromotionType())) {
                            if (CommonConst.PromotionConst.REDUCTION_TYPE_0.equals(promotionInfo.getReductionType())) {
                                // 满减单
                                // 该商品单价价减去的价格 * 商品数量
                                BigDecimal unitDiffPrice = new BigDecimal(promotionInfo.getDiffPrice());
                                sellerDiscountPrice = sellerDiscountPrice.add(unitDiffPrice.multiply(merchCount));
                            } else if (CommonConst.PromotionConst.REDUCTION_TYPE_1.equals(promotionInfo.getReductionType())) {
                                // 满减总
                                // 该商品总价减去的价格
                                BigDecimal sellerDiffPrice = new BigDecimal(promotionInfo.getDiffPrice());
                                sellerDiscountPrice = sellerDiscountPrice.add(sellerDiffPrice);
                            }
                        } else if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4.equals(promotionInfo.getPromotionType())) {
                            // 限促
                            // 限促 - 商品促销单价
                            BigDecimal unitLimitPrice = new BigDecimal(promotionInfo.getLimitRuleList().get(0).getLimitPrice());
                            // 限促 - 商品促销剩余数量
                            BigDecimal merchLimitCount = new BigDecimal(promotionInfo.getLimitRuleList().get(0).getLimitNumber());

                            if (merchLimitCount.compareTo(merchCount) >= 0) {
                                // 折扣总价 = 商品数量 *（实际价格 - 限购价格）
                                sellerDiscountPrice = sellerDiscountPrice.add(merchCount.multiply(unitPrice.subtract(unitLimitPrice)));
                            } else {
                                // 折扣总价 = 限购数量 *（实际价格 - 限购价格）
                                sellerDiscountPrice = sellerDiscountPrice.add(merchLimitCount.multiply(unitPrice.subtract(unitLimitPrice)));
                            }
                        }
                    }
                }
            }

            if (!TextUtils.isEmpty(seller.getMinDeliveryAmt()) && hasMerchesSeled(seller)) {
                sellerTotalPrice = sellerTotalPrice.subtract(sellerDiscountPrice);
                if (sellerTotalPrice.compareTo(new BigDecimal(seller.getMinDeliveryAmt())) < 0) {
                    sellerCannotPay.add(new WrapDealerAttr(seller.getSellerId(), seller.getSellerName(), seller.getMinDeliveryAmt()));
                }
            }
        }

        return sellerCannotPay;
    }

    /**
     * 商家中是否存有选中付款的商品
     *
     * @param seller
     *         商家
     *
     * @return true - 有选中的商品
     */
    private boolean hasMerchesSeled(SellerBean seller) {
        boolean hasMerchSeled = false;
        for (Integer index : seller.getMerchIndex()) {
            hasMerchSeled = ((MerchBean) getItemByPos(index)).isSelected();
            if (hasMerchSeled) {
                break;
            }
        }
        return hasMerchSeled;
    }


    /**
     * 获取商家与被选中的商品对应关系表，用以计算价格 & 删除商品
     *
     * @return 商家与被选中的商品对应关系表
     */
    public SparseArray<List<Integer>> getSellerMerchMap() {
        SparseArray<List<Integer>> sellerMerchMap = new SparseArray<>();

        for (int i = 0; i < getDatas().size(); i++) {
            if (getDatas().get(i) instanceof SellerBean) {
                List<Integer> merchSelIndex = new ArrayList<>();
                SellerBean seller = (SellerBean) getDatas().get(i);
                if (hasMerchesSeled(seller)) {
                    for (int j = 0; j < seller.getMerchIndex().size(); j++) {
                        MerchBean merch = (MerchBean) getDatas().get(seller.getMerchIndex().get(j));
                        if (merch.isSelected()) {
                            merchSelIndex.add(seller.getMerchIndex().get(j));
                        }
                    }
                    sellerMerchMap.put(i, merchSelIndex);
                }
            }
        }

        return sellerMerchMap;
    }


    /**
     * 更新商品的促销词语
     */
    public void updateMerchPromotion(MerchBean merch, List<GiftListBean> giftList) {
        // TODO: 2017/3/12 通知 adapter 更新对应的顶部促销 @lyf #ok
        // TODO: 2017/3/12 通知 adapter 更新对应的底部促销 @lyf #ok
        if (merch.isSelPromotion()) {
            refixedPromotion(merch, giftList, false);
        } else {
            removePromotion(merch);
            merch.setAveragePrice(new BigDecimal(merch.getUnitPrice()));
        }

        noticeUpdate();
        notifyDataSetChanged();
    }

    /**
     * 不使用促销的情况下 移除促销
     *
     * @param merch
     *         商品
     */
    private void removePromotion(MerchBean merch) {
        PromotionBean promotion = (PromotionBean) getDatas().get(((SellerBean) getDatas().get(merch.getSellerIndex())).getPromotionIndex());
        MerchWraper merchWraper = new MerchWraper(merch.getMerchId());

        if (promotion.getMerchWraperList().contains(merchWraper)) {
            promotion.getMerchWraperList().remove(merchWraper);
        }
    }

    /**
     * 修正优惠信息
     */
    private void refixedPromotion(MerchBean merch, List<GiftListBean> giftList, boolean isSelectMerch) {
        PromotionBean promotion = (PromotionBean) getDatas().get(((SellerBean) getDatas().get(merch.getSellerIndex())).getPromotionIndex());
        MerchWraper merchWraper = new MerchWraper(merch.getMerchId());

        if (!isSelectMerch) {
            merchGiftMap.put(merch.getMerchId(), giftList);
        }

        if (merch.isSelected()) {
            merchWraper.setSelected(merch.isSelected());
            merchWraper.setMerchName(merch.getMerchName());
            merchWraper.setPromotionInfo(merch.getSelPromotionInfo());
            merchWraper.setPromotionType(merch.getSelPromotionType());
            merchWraper.setIsValid(merch.getIsPromotion());


            if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_0.equals(merch.getSelPromotionType())) {
                // 满赠
                if (isSelectMerch) {
                    giftList = merchGiftMap.get(merch.getMerchId());
                }

                merchWraper.setGiftList(giftList);
            } else if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4.equals(merch.getSelPromotionType())) {
                // 限促
                PromotionModelListBean promotionInfo = merch.getPromotionModelList().get(merch.getSelPromotionIndex());
                // 限促 - 商品促销单价
                BigDecimal unitLimitPrice = new BigDecimal(promotionInfo.getLimitRuleList().get(0).getLimitPrice());
                // 限促 - 商品促销剩余数量
                BigDecimal merchLimitCount = new BigDecimal(promotionInfo.getLimitRuleList().get(0).getLimitNumber());
                // 限促 - 减去商品促销价后的商品总价
                BigDecimal merchTotalLimitPrice = new BigDecimal(0);
                // 商品数量
                BigDecimal merchCount = new BigDecimal(merch.getMerchQuantity());

                if (merchLimitCount.compareTo(merchCount) >= 0) {
                    // 如果商品数量小于等于限购数量 - 商品数量*限购价格
                    merchTotalLimitPrice = merchTotalLimitPrice.add(unitLimitPrice.multiply(merchCount));
                } else {
                    // 如果商品数量大于限购数量 - 限购数量*限购价格 + 余下数量*实际价格
                    merchTotalLimitPrice = merchTotalLimitPrice.add(unitLimitPrice.multiply(merchLimitCount)).add(merchCount.subtract(merchLimitCount).multiply(new BigDecimal(merch.getUnitPrice())));
                }
                // 设置商品均价
                merch.setAveragePrice(merchTotalLimitPrice.divide(merchCount, 3, BigDecimal.ROUND_HALF_UP));
                merchGiftMap.remove(merch.getMerchId());
            } else {
                merchGiftMap.remove(merch.getMerchId());
            }

            if (promotion.getMerchWraperList().contains(merchWraper)) {
                promotion.getMerchWraperList().remove(merchWraper);
            }

            if (merchWraper.isValid()) {
                promotion.getMerchWraperList().add(merchWraper);
            }
        } else {
            promotion.getMerchWraperList().remove(merchWraper);
        }
    }
}
